package _99练习;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class StudentRunnable2 implements Runnable
{
	
	// 锁
	Lock l = new ReentrantLock();
	
	
	@Override
	public void run() 
	{
		// 定义一个容器 存放1~6
		ArrayList<Integer> needDo = new ArrayList<>();
		Collections.addAll(needDo, 1,2,3,4,5,6);
		
		// 判断还有没有要做的事情
		while(needDo.size()>0)
		{
			System.out.println(Thread.currentThread().getName()+"待做:"+needDo);
			// 先去做第4件事
			if(needDo.contains(4) && l.tryLock())
			{		
				doThings4();
				l.unlock();
				needDo.remove(new Integer(4));
			}
			else
			{
				int num = needDo.get(0);
				if(num==4 && needDo.size()>1)
				{
					num = needDo.get(1);
				}
				switch(num)
				{
				case 1:
					doThings1();
					needDo.remove(new Integer(num));
					break;
				case 2:
					doThings2();
					needDo.remove(new Integer(num));
					break;
				case 3:
					doThings3();
					needDo.remove(new Integer(num));
					break;
				case 5:
					doThings5();
					needDo.remove(new Integer(num));
					break;
				case 6:
					doThings6();
					needDo.remove(new Integer(num));
					break;		
				}
				
			}
		}
	}

	void doThings1()
	{
		System.out.println(Thread.currentThread().getName()+"开始执行1");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"完成执行1");
	}
	void doThings2()
	{
		System.out.println(Thread.currentThread().getName()+"开始执行2");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"完成执行2");
	}
	void doThings3()
	{
		System.out.println(Thread.currentThread().getName()+"开始执行3");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"完成执行3");
	}
	
	void doThings4()
	{
		System.out.println(Thread.currentThread().getName()+"开始执行4");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"完成执行4");
	}
	void doThings5()
	{
		System.out.println(Thread.currentThread().getName()+"开始执行5");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"完成执行5");
	}
	void doThings6()
	{
		System.out.println(Thread.currentThread().getName()+"开始执行6");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"完成执行6");
	}
}

